import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

import redis.clients.jedis.Jedis;


public class RedisTest {

	private Jedis jedis;
	
	@Before 
	public void init() {
		jedis = new Jedis("localhost", 6379);
	}
	
	@Test
	public void testString() {
		jedis.set("name", "张三");
		System.out.println(jedis.get("name"));
		
		jedis.append("name", " is a student");
		System.out.println(jedis.get("name"));
		
		jedis.del("name");
		System.out.println(jedis.get("name"));
		
		jedis.mset("name", "李四", "age", "22", "sex", "女");
		System.out.println(jedis.get("name") + " " + jedis.get("age") + " "  + jedis.get("sex"));
	    
		jedis.incr("age");
		System.out.println(jedis.get("age"));
	}

	@Test
	public void testMap() {
		Map<String, String> map = new HashMap<>();
		map.put("name", "赵六");
		map.put("age", "20");
		map.put("qq", "458238064");
		
		jedis.hmset("user", map);
		
		List<String> rsmap = jedis.hmget("user",	"name", "age", "qq");
		System.out.println(rsmap);
		
		jedis.hdel("user", "age");
		System.out.println(jedis.hmget("user", "age"));
		System.out.println(jedis.hlen("user"));
		System.out.println(jedis.exists("user"));
		System.out.println(jedis.hkeys("user"));
		System.out.println(jedis.hvals("user"));
		
		Iterator<String> it = jedis.hkeys("user").iterator();
		String key = null;
		while(it.hasNext()) {
			key = it.next();
			System.out.println(key + ": " + jedis.hmget("user", key));
		}
	}
	
	@Test
	public void testList() {
		jedis.lpush("java framework", "spring");
		jedis.lpush("java framework", "struts2");
		jedis.lpush("java framework", "hibernate");
		System.out.println(jedis.lrange("java framework", 0, -1));
		
		jedis.del("java framework");
		jedis.rpush("java framework", "spring");
		jedis.rpush("java framework", "struts2");
		jedis.rpush("java framework", "hibernate");
		System.out.println(jedis.lrange("java framework", 0, -1));
	}
	
	@Test
	public void testSet() {
		jedis.sadd("user1", "liuling");
		jedis.sadd("user1", "ling");
		jedis.sadd("user1", "john");
		jedis.sadd("user1", "mary");
		jedis.sadd("user1", "judy");
		
		jedis.srem("user1", "judy");
		System.out.println(jedis.smembers("user1"));
		System.out.println(jedis.sismember("user1", "judy"));
		System.out.println(jedis.srandmember("user1"));
		System.out.println(jedis.scard("user1"));		
	}
	
	@Test public void testSort() {
		jedis.del("a");
		jedis.lpush("a", "1");
		jedis.rpush("a", "6");
		jedis.rpush("a", "4");
		jedis.rpush("a", "7");
		jedis.rpush("a", "5");
		
		System.out.println(jedis.lrange("a", 0, -1));
		System.out.println(jedis.sort("a"));
		System.out.println(jedis.lrange("a", 0, -1));
	}
	
	@Test
	public void testJedisPool() {
		RedisUtil.getJedis().set("newname", "中文测试");
		System.out.println(RedisUtil.getJedis().get("newname"));
	}
}
